package com.dbapp.garden.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dbapp.garden.entity.SysRole;
import com.dbapp.garden.entity.SysRoleResource;
import com.dbapp.garden.mapper.SysRoleMapper;
import com.dbapp.garden.mapper.SysRoleResourceMapper;
import com.dbapp.garden.service.SysRoleService;

@Service
public class SysRoleServiceImpl implements SysRoleService {

	@Autowired
	private SysRoleMapper sysRoleMapper;

	@Autowired
	private SysRoleResourceMapper sysRoleResourceMapper;

	@Override
	public List<SysRole> getRoleList(Map<String, Object> map) {
		if (map == null) {
			return null;
		}
		return sysRoleMapper.getRoleList(map);
	}

	@Override
	public Integer getRoleCount(Map<String, Object> map) {
		if (map == null) {
			return null;
		}
		return sysRoleMapper.getRoleCount(map);
	}

	@Override
	public SysRole findRoleByName(Map<String,Object> map) {

		return sysRoleMapper.findRoleByName(map);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer saveRole(SysRole role, List<Integer> resIds) {
		
		if (role.getId() == null) {
			sysRoleMapper.insertSelective(role);
			
			List<SysRoleResource> sysRoleResourceList = resIds.stream().map(resId -> {
				SysRoleResource sysRoleResource = new SysRoleResource();
				sysRoleResource.setResourceId(resId);
				sysRoleResource.setRoleId(role.getId());
				sysRoleResource.setCreateTime(new Date());
				sysRoleResource.setUpdateTime(new Date());
				return sysRoleResource;
			}).collect(Collectors.toList());
			
			return sysRoleResourceMapper.batchInsert(sysRoleResourceList);
		} else {
			List<SysRoleResource> sysRoleResourceList = resIds.stream().map(resId -> {
				SysRoleResource sysRoleResource = new SysRoleResource();
				sysRoleResource.setResourceId(resId);
				sysRoleResource.setRoleId(role.getId());
				sysRoleResource.setCreateTime(new Date());
				sysRoleResource.setUpdateTime(new Date());
				return sysRoleResource;
			}).collect(Collectors.toList());
			sysRoleMapper.updateByPrimaryKeySelective(role);
			// 删除角色资源表中的授权资源，然后在插入
			sysRoleResourceMapper.deleteByRoleId(role.getId());
			return sysRoleResourceMapper.batchInsert(sysRoleResourceList);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer deleteRole(Integer roleId) {

		sysRoleResourceMapper.deleteByRoleId(roleId);
		return sysRoleMapper.deleteByPrimaryKey(roleId);
	}

	@Override
	public SysRole findRoleById(Integer id) {
		if (id == null) {
			return null;
		}
		return sysRoleMapper.selectByPrimaryKey(id);
	}
}
